package com.yhk.wuchat.common.common.interceptor;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.ContentType;
import com.yhk.wuchat.common.common.exception.HttpErrorEnum;
import com.yhk.wuchat.common.user.service.LoginService;
import org.apache.commons.io.Charsets;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.Optional;

/**
 * @version 1.0
 * @Author moresuo
 * @Date 2024/4/8 14:47
 * @注释
 */

/**
 * token拦截器，从用户传来的Token中获取uid,校验身份
 *
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {
    public static final String HEAD_AUTHORIZATION ="Authorization";
    public static final String BEARER_ = "Bearer ";
    public static final String UID = "uid";

    @Resource
    private LoginService loginService;

    /**
     * 前置拦截器
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token
        String token=getToken(request);
        //获取用户id
        Long uid = loginService.getValidUid(token);
        if(Objects.nonNull(uid)){
            //用户有登录态
            request.setAttribute(UID,uid);
        }else{
            boolean isPublicURI = isPublicURI(request);
            if(!isPublicURI){
                //非公共接口，需要登录态
                HttpErrorEnum.ACCESS_DENIED.sendHttpError(response);
                return false;
            }
        }
        return true;
    }

    private boolean isPublicURI(HttpServletRequest request){
        String requestURI = request.getRequestURI();
        String[] split = requestURI.split("/");
        boolean isPublicURI = split.length > 2 && "public".equals(split[3]);
        return isPublicURI;
    }

    /**
     * 获取token
     * @param request
     * @return
     */
    private String getToken(HttpServletRequest request) {
        String authorization = request.getHeader(HEAD_AUTHORIZATION);
        return Optional.ofNullable(authorization).
                filter(h->h.startsWith(BEARER_)).
                map(h->h.replaceFirst(BEARER_,""))
                .orElse(null);
    }
}
